package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.AdChannelService;
import com.heima.model.admin.dtos.ChannelDto;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Transactional
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {


    /**
     * 删除频道
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteById(Integer id) {
        // 1 参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 2 执行删除(先查后删除)
        AdChannel channel = getById(id);
        if (channel == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        if (channel.getIsDefault()) {// 默认频道
            return ResponseResult.errorResult(AppHttpCodeEnum.CHANNEL_ISDEFAULT_INVALID);
        }
        if (channel.getStatus()) { // 启用状态
            return ResponseResult.errorResult(AppHttpCodeEnum.ADMIN_CHANNEL_ISSTATUS_ERROR);
        }

        removeById(id);

        // TODO 频道下存在文章，不允许删除频道
//        int i = 1 / 0;

        //3 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 修改&状态
     * @param adChannel
     * @return
     */
    @Override
    public ResponseResult update(AdChannel adChannel) {
        //1 参数校验
//        if (adChannel == null || StringUtils.isBlank(adChannel.getName())
//                ) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
//        }
//        if (adChannel.getId() == null) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
//        }

        //2 执行修改(先查后改)
        AdChannel channel = getById(adChannel.getId());
        if (channel == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        if (adChannel.getIsDefault()) {  // 是默认
            // 查询原有的默认的频道，更新为非默认
            LambdaQueryWrapper<AdChannel> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AdChannel::getIsDefault, 1);
            AdChannel one = getOne(wrapper);

            // 判断是否存在默认频道
            if (one != null) {
                // 更新为非默认
                one.setIsDefault(false);
                updateById(one);
            }
        }
        updateById(adChannel);

        //3 返回结果

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 新增
     * @param adChannel
     * 优化：前端添加是否默认
     * @return
     */
    @Override
    public ResponseResult insert(AdChannel adChannel) {
        // 1 参数校验
//        if (adChannel == null || StringUtils.isBlank(adChannel.getName())) {
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
//        }

        // 2 执行新增

        adChannel.setCreatedTime(new Date());

        if (adChannel.getIsDefault()) {  // 是默认
            // 查询原有的默认的频道，更新为非默认
            LambdaQueryWrapper<AdChannel> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AdChannel::getIsDefault, 1);
            AdChannel one = getOne(wrapper);

            // 判断是否存在默认频道
            if (one != null) {
                // 更新为非默认
                one.setIsDefault(false);
                updateById(one);
            }
        }
//        if (true) {
//            // 程序员主动抛出异常（可预知异常）
//            // throw new RuntimeException("默认频道已删除");
//            CustException.cust(AppHttpCodeEnum.NEED_ADMIND);
//        }


        save(adChannel);
        // 3 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 条件查询频道列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByNameAndPage(ChannelDto dto) {
        // 1 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        // 检查分页
        dto.checkParam();

        // 2 构建查询条件执行查询
        // 分页
        IPage<AdChannel> pageParam = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<AdChannel> query = new LambdaQueryWrapper<>();
        // 构建查询条件
        // 频道模糊查询
        if (StringUtils.isNotBlank(dto.getName())) {
//            query.like("name", dto.getName());
            query.like(AdChannel::getName, dto.getName());
        }
        // 状态
        if (dto.getStatus() != null) {
            query.eq(AdChannel::getStatus, dto.getStatus());
        }

        IPage<AdChannel> pageResult = page(pageParam, query);

        // 3 封装返回结果
        ResponseResult result = new PageResponseResult( dto.getPage(), dto.getSize(),
                pageResult.getTotal(), pageResult.getRecords() );
        return result;
    }


}
